import React, { Component } from 'react'
import { Link } from 'react-router-dom'
import { Breadcrumb, Icon } from 'antd'
import pathToRegexp from 'path-to-regexp'
import styles from './Bread.less'
import _menusData from '@/config/menus'
import { cloneDeep } from 'lodash'
const BreadcrumbItem = Breadcrumb.Item


class Bread extends Component {
  getPathArr() {
    let pathArr = []
    const { pathname } = this.props.location
    const menusData = cloneDeep(_menusData)
    let currentRoute = menusData.filter(_=>_.route && pathToRegexp(_.route).exec(pathname))[0]
    let homeRoute = menusData.filter(_=>_.route && _.isHome)[0]
    if (!currentRoute) {
      return [{
        id: 404,
        name: 'Not Found'
      }]
    }
    pathArr.push(homeRoute)
    if (currentRoute.isHome) {
      return pathArr
    }
    if (currentRoute.pid) {
      pathArr = pathArr.concat(this.getParent(currentRoute.pid))
    }
    pathArr.push(currentRoute)
    return pathArr
  }
  getParent(pid) {
    const menusData = cloneDeep(_menusData)
    let parent = menusData.filter(_=>_.id==pid)
    if (parent[0].pid) {
      return parent.concat(this.getParent(parent[0].pid))
    }
    return parent
  }
  renderBreads() {
    const pathArr = this.getPathArr()
    const breads = pathArr.map((item, index) => {
      const content = (
        <span>
          {item.icon ? <Icon type={item.icon} style={{ marginRight: 4 }}></Icon> : ''} {item.name}
        </span>
      )
      return (
        <BreadcrumbItem key={index}>
          {content}
        </BreadcrumbItem>
      )
    })
    return breads
  }
  render() {
    return (
      <div className={styles.bread}>
        <Breadcrumb>
          {this.renderBreads()}
        </Breadcrumb>
      </div>
    )
  }
}

export default Bread
